﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Compression;
using System.IO;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace XMouse360
{
	public class KeymapIO
	{
		private string currentKeymapFilePath; //Save will compare this to 'path' and if it's the same and there's a change in the keymap, raise KeymapChanged

		public static event EventHandler KeymapChanged;
		public delegate void KeymapFileChangedEventHandler(string filename, EventArgs e);
		public static readonly string Suffix = "kmp";
		private static Dictionary<Keymap, string> openKeymaps;//<KeymapTitle,FileName>

		private static bool isLoaded = false;


		public static Keymap[] Keymaps
		{
			get
			{
				if (!isLoaded)
					UpdateDictionary();
				Keymap[] array = new Keymap[openKeymaps.Count];
				openKeymaps.Keys.CopyTo(array, 0);
				return array.OrderBy(x => x.rank).ToArray<Keymap>();
			}
		}

		public static Keymap Load(int rank)
		{
			if (!isLoaded)
				UpdateDictionary();
			if (rank < Keymaps.Length)
			{
				return Keymaps[rank];
			}
			else throw new IndexOutOfRangeException("Rank of requested Keymap is out of range");
		}

		private static Keymap Read(string path)
		{
			XmlSerializer reader = new XmlSerializer(typeof(Keymap));
			Keymap map = new Keymap();
			StreamReader sr = new StreamReader(new BufferedStream(File.OpenRead(path)));
			map = (Keymap)reader.Deserialize(sr);
			sr.Close();			
			return map;
		}

		private static void write(Keymap map, string path)
		{
			XmlSerializer writer = new XmlSerializer(typeof(Keymap));
			StreamWriter sw = new StreamWriter(new BufferedStream(File.OpenWrite(path)));
			writer.Serialize(sw, map);
			sw.Close();
		}

		public static void UpdateKeymap(Keymap map)
		{
			write(map, openKeymaps[map]);

		}

		public static void WriteNewKeymapToDefault(Keymap map, string filename)
		{
			XmlSerializer writer = new XmlSerializer(typeof(Keymap));
			StreamWriter sw = File.CreateText(System.IO.Path.Combine(Properties.Settings.Default.DefaultDirectory, filename));
			writer.Serialize(sw, map);
			sw.Close();
			
		}

		public static void ChangeDirectory(string directory)
		{
			Properties.Settings.Default.DefaultDirectory = directory;
			UpdateDictionary();
		}

		/// <summary>
		/// Updates openKeymaps with all the files in the default directory
		/// </summary>
		/// <returns></returns>
		public static void UpdateDictionary()
		{
			string directory = Properties.Settings.Default.DefaultDirectory;
			string[] filenames = System.IO.Directory.GetFiles(directory);
			openKeymaps = new Dictionary<Keymap, string>();
			foreach (string file in filenames)
			{
				Keymap map = Read(System.IO.Path.Combine(directory, file));
				openKeymaps.Add(map, System.IO.Path.Combine(directory, file));
			}
			isLoaded = true;
			


		}
	}
}
